import java.lang.reflect.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class AutoForm {
	public static void makeFormForObject(Object obj){
		if(obj != null)
			makeFormForClass(obj.getClass());
	}
	
	public static void makeFormForClass(String className) throws ClassNotFoundException{
		makeFormForClass(Class.forName(className));
	}
	
	public static void makeFormForClass(Class c){
		if(c == null) return;
		
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JFrame frame = new JFrame(c.getName());
		JPanel pane = new JPanel(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();
		gc.insets = new Insets(2,2,2,2);
		gc.gridx = 0;
		gc.gridy = 0;
		
		for(Field f : c.getDeclaredFields()){
			if(f.isAnnotationPresent(AutoFormAnnotation.class)){
				AutoFormAnnotation afa = f.getAnnotation(AutoFormAnnotation.class);
				JLabel label = new JLabel(afa.label());
				JComponent component = null;
				
				if(afa.type() == AutoFormField.RadioButton){
					component = new JPanel();
					ButtonGroup bg = new ButtonGroup();
					
					if(afa.options().length > 0){
						for(String s : afa.options()){
							JRadioButton rb = new JRadioButton(s);
							rb.setSelected(true);
							bg.add(rb);
							component.add(rb);
						}
					}					
				}else if(afa.type() == AutoFormField.CheckBox){
					component = new JCheckBox();
					
				}else{
					JTextField t = new JTextField();
					if(afa.options().length > 0 && afa.options()[0].length() > 0){
						t.setColumns(Integer.parseInt(afa.options()[0]));
					}else{
						t.setColumns(10);
					}
					component = t;
				}
				
				if(component != null){
					component.setAlignmentX(Component.LEFT_ALIGNMENT);
					
					gc.anchor = GridBagConstraints.EAST;
					pane.add(label, gc);
					gc.gridx = 1;
					
					gc.anchor = GridBagConstraints.WEST;
					pane.add(component, gc);
					
					gc.gridy++;
					gc.gridx = 0;
				}
			}
		}
		
		JButton ok = new JButton("OK");
		ok.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
			}
		});
		gc.gridx = 1;
		gc.anchor = GridBagConstraints.EAST;
		pane.add(ok, gc);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(pane);
		
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
}
